<script lang="ts">
import { useI18n } from 'vue-i18n'

export default {
	name: 'LanguageSwitch',

	data() {
		return {
			languages: [
				{ key: 'zh-CN', label: '', icon: '🇨🇳' },
				{ key: 'en-US', label: '', icon: '🇺🇸' },
				{ key: 'ru-RU', label: '', icon: '🇷🇺' }
			]
		}
	},

	setup() {
		const languageStore = useLanguageStore()
		const { t } = useI18n()
		const { currentLanguage } = storeToRefs(languageStore)
		return {
			languageStore,
			t,
			currentLanguage
		}
	},

	mounted() {
		this.updateLanguageLabels()
	},

	methods: {
		updateLanguageLabels() {
			this.languages = [
				{ key: 'zh-CN', label: this.t('语言.中文'), icon: '🇨🇳' },
				{ key: 'en-US', label: this.t('语言.英文'), icon: '🇺🇸' },
				{ key: 'ru-RU', label: this.t('语言.俄文'), icon: '🇷🇺' }
			]
		},

		handleLanguageChange(lang: string) {
			this.languageStore.setLanguage(lang as 'zh-CN' | 'en-US' | 'ru-RU')
			this.updateLanguageLabels()
		},

		getCurrentLanguageIcon(lang: string) {
			const language = this.languages.find(l => l.key === lang)
			return language ? language.icon : '🇨🇳'
		},

		getCurrentLanguageLabel(lang: string) {
			const language = this.languages.find(l => l.key === lang)
			return language ? language.label : this.t('语言.中文')
		}
	},

	watch: {
		currentLanguage: {
			handler() {
				this.updateLanguageLabels()
			},
			immediate: true
		}
	}
}
</script>

<template>
	<a-dropdown :trigger="['click']" placement="bottomRight">
		<a-button type="text" class="language-switch">
			<span class="mr-1">{{ getCurrentLanguageIcon(currentLanguage) }}</span>
			<span>
				{{ getCurrentLanguageLabel(currentLanguage) }}
			</span>
		</a-button>
		<template v-slot:overlay>
			<a-menu>
				<a-menu-item
					v-for="lang in languages"
					:key="lang.key"
					@click="handleLanguageChange(lang.key)"
					:class="{ 'ant-menu-item-selected': currentLanguage === lang.key }">
					<span class="mr-2">{{ lang.icon }}</span>
					<span>{{ lang.label }}</span>
				</a-menu-item>
			</a-menu>
		</template>
	</a-dropdown>
</template>

<style scoped>
.language-switch {
	color: inherit;
}
.language-switch:hover {
	color: #1890ff;
}
</style>
